import time

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.shortcuts import redirect
from .models import Item
from home.views import user_check



def get_all_item(type1, type2):
    """
    根据类型获取所有列表
    """
    items = Item.objects.filter(func_type=type1, item_type=type2)  # 根据类型获取列表
    keys = set([i.lv for i in items])
    keys = list(keys)
    keys.sort()
    items_splite = [[] for i in keys]
    cnt = 0
    for item in items:
        i = keys.index(item.lv)
        cnt += 1
        new_item = {
            "id": item.number,
            "cnt": cnt,
            "name": item.name,
            "url": f"/item/{item.md5}",
            "lv": item.lv,
            "mtime": item.modified_time,
            "show": item.show,
        }
        items_splite[i].append(new_item)
    for i in range(len(items_splite)):
        items_splite[i] = sorted(
            items_splite[i], key=lambda x: (x["id"], x["name"], x["mtime"])
        )
    return items_splite


def index(request, type1):
    """
    讲义或练习首页
    """
    context = user_check(request)
    
    if type1 == "lesson":
        context["title"] += "-讲义"
        return render(request, "teach/lesson_index.html", context)
    elif type1 == "training":
        context["title"] += "-训练"
        return render(request, "teach/training_index.html", context)

def checkSubject(type,context):
    print("讲义/练习页：context",context)
    subjects=context["myuser"].subjects.all()
    checkDic={"py":"PYTHON","sc":"SCRATCH","cpp":"CPP"}
    for subject in subjects:
        # 忽略大小写一致就行
        if checkDic[type]== subject.name.upper():
            return True
    return False


@login_required
def item_list(request, type1, type2):
    """
    列表
    """
    print("item_list:type1->",type1, "type2->", type2)
    context = user_check(request)
    context["username"] = request.user.username
    if checkSubject(type2,context):
        datas = get_all_item(type1, type2)
        context["title"] += "-"+type2
        if type1 == "lesson":
            context["title"] += "-讲义列表"
            context["lesson_type"] = type2
            context["lessons"] = datas
            return render(request, "teach/lesson_list.html", context)
        elif type1 == "training":
            for data in datas:
                cnt = 0
                for i in data:
                    cnt += 1
                    i["cnt"] = cnt
            newdatas = {}
            for data in datas:
                newdatas[data[0]['lv']] = data
            for i in newdatas:
                data = {}
                for j in newdatas[i]:
                    if not j['id'] in data:
                        data[j['id']] = [j]
                    else:
                        data[j['id']].append(j)
                newdatas[i] = data
            datas = newdatas
            context["title"] += "-训练列表"
            context["training_type"] = type2
            context["trainings"] = datas
            return render(request, "teach/training_list.html", context)
    else:
        context["message_danger"] = "抱歉，您没有权限访问该内容，请联系管理员获取。"
        # return render(request, "home/index.html", context)
        if type1 == "lesson":
            return render(request, "teach/lesson_index.html", context)
        elif type1 == "training":
            return render(request, "teach/training_index.html", context)
        


@login_required
def item_detail(request, url):
    """
    根据md5值获取讲义并返回
    """
    context = user_check(request)
    if request.user.is_authenticated:
        if request.user.is_active:
            context["username"] = request.user.username
            item = Item.objects.filter(md5=url)

            if item:
                item = item[0]
                real_url = item.url
                if not real_url.startswith("/"):
                    real_url = "/" + real_url
                context["real_url"] = (
                    real_url + f"?t={time.time()}"
                )  # 返回的地址加上时间信息用来刷新iframe，否则iframe不会刷新
                context["title"] += f"-{item.name}"
                if real_url.endswith(".pdf"):
                    context["ispdf"] = True
                next_url = request.GET.get('next')
                if next_url:
                    return redirect(next_url, message_success="登陆成功。")
                else:
                    return render(request, "teach/item.html", context)
            else:
                return redirect("/")  # 没找到就直接返回首页

        else:
            context["message_danger"] = "抱歉，用户已被禁用。"
            context["title"] += "-登陆"
            return render(request, "home/login.html", context)
    else:
        context["message_danger"] = "请先登陆。"
        context["title"] += "-登陆"
        return render(request, "/login/", context)
